package com.comtime.smartbox;

import android.animation.ValueAnimator;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TextView;

import com.comtime.greendaodemo.DeviceInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.mybox.OADActivity;
import com.comtime.service.DownloadService;
import com.comtime.service.MyService;
import com.comtime.smartkilimanjaro.R;
import com.comtime.usercenter.UserInfoActivity;
import com.comtime.utils.LogUtils;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.Util;
import com.comtime.view.MyDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;
import com.comyou.customviews.SlideListView;
import com.comyou.roundimageview.RoundedImageView;
import com.nineoldandroids.view.ViewHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

@SuppressWarnings({ "unused", "deprecation" })
public class MainActivity extends TabActivity implements DrawerListener,
		OnClickListener {

	public static String EXIT = "com.comtime.samrtbox.exit";
	public static String SELESTDEVICE = "com.comtime.samrtbox.selestdevice";
	public static String ACTION_REMINDINFO = "com.comtime.samrtbox.remindinfo.start";

	MySharedPreferences mySharedPreferences;
	HBApplication application;
	public TabHost tabHost;

	LinearLayout line_menu;
	
	//浮标
	ImageView btn_logo;

	// 侧边栏
	private static final String TAG = "tag";
	RoundedImageView image_photo;
	TextView tv_name;
	RelativeLayout relate_one, relate_two, relate_three, relate_four,
			relate_five;
	View v_box_one, v_box_two, v_box_three, v_box_four, v_box_five;

	DrawerLayout mDrawerLayout;
	// private RelativeLayout mainLayout;
	private RelativeLayout leftLayout;
	private RelativeLayout rightLayout;

	// 右侧边栏

	SlideListView right_ListView;// 箱包列表
	List<DeviceInfo> deviceInfos;// 箱包
	RelativeLayout line_add_box;

	// private GestureDetector mGestureDetector;

	private static final int SPEED = 30;
	private boolean bIsScrolling = false;
	private int iLimited = 0;
	private int mScroll = 0;
	private View mClickedView = null;

	DataBaseUtil dataBaseUtil;

	float density = 0;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		hide(getWindow().getDecorView());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mySharedPreferences = MySharedPreferences.getInstance(this);
		density = getResources().getDisplayMetrics().density;
		dataBaseUtil = DataBaseUtil.getInstance(this);
		registBroatcast();
		application = (HBApplication) getApplication();
		Intent intent = new Intent(this, MyService.class);
		startService(intent);
		btn_logo=(ImageView) findViewById(R.id.btn_logo);
		btn_logo.setOnClickListener(this);
		initLeftMenu();
		initRightMenu();
		setUpViews();
		if (!getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {

			MyConfig.canUse = false;
		} else {
			MyConfig.canUse = true;
		}
		
		 checkUpdate();
	}

	// 左侧边栏
	void initLeftMenu() {
		mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerLayout);
		mDrawerLayout.setScrimColor(Color.TRANSPARENT);
		mDrawerLayout.setDrawerListener(this);
		leftLayout = (RelativeLayout) findViewById(R.id.leftLayout);
		leftLayout.setOnClickListener(this);
		image_photo = (RoundedImageView) findViewById(R.id.image_photo_left);
		image_photo.setOnClickListener(this);
		tv_name = (TextView) findViewById(R.id.tv_account);
		tv_name.setText(mySharedPreferences.getUserName());

		relate_one = (RelativeLayout) findViewById(R.id.relate_box_one);
		//relate_two = (RelativeLayout) findViewById(R.id.relate_box_two);
		relate_three = (RelativeLayout) findViewById(R.id.relate_box_three);
		relate_four = (RelativeLayout) findViewById(R.id.relate_box_four);
		relate_five = (RelativeLayout) findViewById(R.id.relate_box_five);

		relate_one.setOnClickListener(this);
		//relate_two.setOnClickListener(this);
		relate_three.setOnClickListener(this);
		relate_four.setOnClickListener(this);
		relate_five.setOnClickListener(this);

		v_box_one = findViewById(R.id.v_box_one);
		//v_box_two = findViewById(R.id.v_box_two);
		v_box_three = findViewById(R.id.v_box_three);
		v_box_four = findViewById(R.id.v_box_four);
		v_box_five = findViewById(R.id.v_box_five);

	}

	/**
	 * 右侧边栏
	 */
	void initRightMenu() {
		rightLayout = (RelativeLayout) findViewById(R.id.rightLayout);
		rightLayout.setOnClickListener(this);
		View v = LayoutInflater.from(this).inflate(R.layout.item_add_box, null);
		line_add_box = (RelativeLayout) v.findViewById(R.id.line_add_box);
		line_add_box.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mySharedPreferences.saveBluAdress("");
				application.swDevicesList.get(0).remove();
				right_ListView.deleteItem();
				deviceListChangeUI();
				Intent intent = new Intent(MyService.ACTION_UPDATE_UI);
				sendBroadcast(intent);
				mDrawerLayout.closeDrawers();
			}
		});
		right_ListView = (SlideListView) findViewById(R.id.right_listview);
		right_ListView.setOnItemClickListener(itemClickListener);
		right_ListView.setRightBtnWidth(dp2px(90));
		right_ListView.addFooterView(v);
		right_ListView.setAdapter(rightAdapter);
	}

	private void registBroatcast() {
		IntentFilter filter = new IntentFilter(EXIT);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(MyService.ACTION_UPDATE_UI);
		filter.addAction(MyService.ACTION_MAIN_DEVICEUI_CHANGE);
		filter.addAction(MyService.ACTION_CHECKUSER_RESULT);
		filter.addAction(MyService.ACTION_CHECKUSER_RESULT);
		filter.addAction(MyService.ACTION_FIST_ADDUSER);
		filter.addAction(MyService.ACTION_ShowOAD);
		
		registerReceiver(receiver, filter);
	}

	ListView listView;

	private void setUpViews() {

		tabHost = this.getTabHost();
		TabHost.TabSpec spec;
		Intent intent;

		intent = new Intent().setClass(this, Activity_0.class);
		spec = tabHost.newTabSpec("Home").setIndicator("Home")
				.setContent(intent);
		tabHost.addTab(spec);
		/**
		 * 
		 */
		intent = new Intent().setClass(this, Activity_1.class);
		spec = tabHost.newTabSpec("Date").setIndicator("Date")
				.setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Activity_2.class);
		spec = tabHost.newTabSpec("Info").setIndicator("Info")
				.setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Activity_3.class);

		spec = tabHost.newTabSpec("Set").setIndicator("Set").setContent(intent);
		tabHost.addTab(spec);

		intent = new Intent().setClass(this, Activity_4.class);

		spec = tabHost.newTabSpec("His").setIndicator("His").setContent(intent);
		tabHost.addTab(spec);

		tabHost.setCurrentTab(0);

	}

	String action = "";
	int select_tag = 0;
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
			if (action.equals(Intent.ACTION_SCREEN_OFF)) {
				if (Util.isAppOnForeground(context)) {
					backRun();
				}

			} else if (action.equals(EXIT)) {
				unBindService();
				MainActivity.this.finish();

				System.exit(0);
			} else if (action.equals(MyService.ACTION_MAIN_DEVICEUI_CHANGE)) {
				// 设备列表变化
				deviceListChangeUI();
			}else if(action.equals(MyService.ACTION_CHECKUSER_RESULT)){
				//用户验证失败
				showCancelDialog(getText(R.string.user_check_fail).toString());
				
				if(deviceInfos!=null&&deviceInfos.size()>0){
					
					dataBaseUtil.deleteDeviceInfo(
							mySharedPreferences.getPhoneNum(),
							deviceInfos.get(deviceInfos.size()-1).getMac());
					application.swDevicesList.get(0).remove();
					mySharedPreferences.saveBluAdress("");

					rightAdapter.notifyDataSetChanged();

					deviceInfos = dataBaseUtil
							.loadDeviceInfo(mySharedPreferences.getPhoneNum());
					
					
					
					if (deviceInfos != null && deviceInfos.size() > 0) {
						mySharedPreferences.saveBluAdress(deviceInfos.get(0)
								.getMac());

					}
					right_ListView.deleteItem();
					deviceListChangeUI();
					Intent intent_2 = new Intent(MyService.ACTION_UPDATE_UI);
					sendBroadcast(intent_2);

					intent_2 = new Intent(MyService.ACTION_MYSERVICE);
					intent_2.putExtra(MyService.VALUE_TAG, 1);
					sendBroadcast(intent_2);
				}
			
				
			}else if(action.equals(MyService.ACTION_FIST_ADDUSER)){
				LogUtils.e(TAG, "ACTION_FIST_ADDUSER ");
				Intent intent2=new Intent(MainActivity.this, UserInfoActivity.class);
				intent2.putExtra(UserInfoActivity.Extra_NeedAddFirstUser, true);
				startActivity(intent2);
			}else if (action.equals(MyService.ACTION_ShowOAD)) {
				LogUtils.e(TAG, "ACTION_ShowOAD ");
				showNeedOADDialog();
			}
		}
	};

	protected void showNeedOADDialog() {
		final MyDialog myDialog;
		myDialog = new MyDialog(MainActivity.this);
		myDialog.setContent(R.string.need_OAD);
		myDialog.setLeftButtonText(R.string.cancel);
		myDialog.setRightButtonText(R.string.ok);
		myDialog.setCancelable(false);
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.dismiss();
			}
		});
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.dismiss();
				Intent intent = new Intent(MainActivity.this, OADActivity.class);
				startActivity(intent);
			}
		});
		myDialog.show();
	}


	/**
	 * 设备列表变化
	 */
	void deviceListChangeUI() {
		deviceInfos = dataBaseUtil.loadDeviceInfo(mySharedPreferences
				.getPhoneNum());
		if (deviceInfos != null && deviceInfos.size() >= 3) {
			line_add_box.setVisibility(View.GONE);

		} else {
			line_add_box.setVisibility(View.VISIBLE);

		}
		rightAdapter.notifyDataSetChanged();
	}

	void unBindService() {
		Intent intent = new Intent(this, MyService.class);
		stopService(intent);
	}

	void backRun() {
		// broadcastAll();

		Intent i = new Intent(Intent.ACTION_MAIN);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.addCategory(Intent.CATEGORY_HOME);
		startActivity(i);
	}

	public void moveAction(final View v) {

		ValueAnimator progressAnimator = ValueAnimator.ofFloat(0, 1);
		progressAnimator.setDuration(500);
		progressAnimator.setInterpolator(new LinearInterpolator());
		progressAnimator
				.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

					@Override
					public void onAnimationUpdate(ValueAnimator animation) {
						progress = (Float) animation.getAnimatedValue();

						RelativeLayout.LayoutParams layoutParams = (LayoutParams) v
								.getLayoutParams();

						layoutParams.leftMargin = -(int) (v.getWidth() * progress);

						v.setLayoutParams(layoutParams);
					}

				});
		progressAnimator.start();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {// 有效
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			backRun();

			return true;// 返回true，把事件消费掉，不会继续调用onBackPressed

		}
		return super.dispatchKeyEvent(event);
	}

	public static void hide(View decorView) {
		if (!hasSmartBar())
			return;

		try {
			@SuppressWarnings("rawtypes")
			Class[] arrayOfClass = new Class[1];
			arrayOfClass[0] = Integer.TYPE;
			Method localMethod = View.class.getMethod("setSystemUiVisibility",
					arrayOfClass);
			Field localField = View.class
					.getField("SYSTEM_UI_FLAG_HIDE_NAVIGATION");
			Object[] arrayOfObject = new Object[1];
			try {
				arrayOfObject[0] = localField.get(null);
			} catch (Exception e) {

			}
			localMethod.invoke(decorView, arrayOfObject);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * SmartBar
	 * 
	 * @return
	 */
	public static boolean hasSmartBar() {

		String string = android.os.Build.FINGERPRINT.toLowerCase();
		Log.i("tag", string);
		try {
			Method method = Class.forName("android.os.Build").getMethod(
					"hasSmartBar");
			return ((Boolean) method.invoke(null)).booleanValue();
		} catch (Exception e) {
		}

		if (string.contains("meizu") || string.contains("flyme")) {
			return true;
		} else if (Build.DEVICE.equals("mx") || Build.DEVICE.equals("m9")) {
			return false;
		}
		return false;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// if (MyConfig.UMENG_SDK_OPEN) {
		// MobclickAgent.onResume(this);
		// }
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		 deviceListChangeUI();
		 
		 tv_name.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				 tv_name.setText(mySharedPreferences.getUserName());
			}
		}, 400);
		
		 
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent i = new Intent(Intent.ACTION_MAIN);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.addCategory(Intent.CATEGORY_HOME);
		startActivity(i);
	}

	void showCancelDialog(String str) {
		final MyDialog myDialog = new MyDialog(MainActivity.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.ok));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				myDialog.dismiss();
			}
		});
		myDialog.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.relate_box_one:
			v_box_one.setVisibility(View.VISIBLE);
			//v_box_two.setVisibility(View.INVISIBLE);
			v_box_three.setVisibility(View.INVISIBLE);
			v_box_four.setVisibility(View.INVISIBLE);
			v_box_five.setVisibility(View.INVISIBLE);
			tabHost.setCurrentTabByTag("Home");
			mDrawerLayout.closeDrawers();mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
			break;
		/*case R.id.relate_box_two:
			v_box_one.setVisibility(View.INVISIBLE);
			v_box_two.setVisibility(View.VISIBLE);
			v_box_three.setVisibility(View.INVISIBLE);
			v_box_four.setVisibility(View.INVISIBLE);
			v_box_five.setVisibility(View.INVISIBLE);

			tabHost.setCurrentTabByTag("Date");
			mDrawerLayout.closeDrawers();mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
			break;*/
		case R.id.relate_box_three:
			v_box_one.setVisibility(View.INVISIBLE);
			//v_box_two.setVisibility(View.INVISIBLE);
			v_box_three.setVisibility(View.VISIBLE);
			v_box_four.setVisibility(View.INVISIBLE);
			v_box_five.setVisibility(View.INVISIBLE);
			tabHost.setCurrentTabByTag("Info");
			mDrawerLayout.closeDrawers();mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
			break;
		case R.id.relate_box_four:
			v_box_one.setVisibility(View.INVISIBLE);
			//v_box_two.setVisibility(View.INVISIBLE);
			v_box_three.setVisibility(View.INVISIBLE);
			v_box_four.setVisibility(View.VISIBLE);
			v_box_five.setVisibility(View.INVISIBLE);

			tabHost.setCurrentTabByTag("Set");
			mDrawerLayout.closeDrawers();mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
			break;
		case R.id.relate_box_five:
			// 历史记录
			v_box_one.setVisibility(View.INVISIBLE);
			//v_box_two.setVisibility(View.INVISIBLE);
			v_box_three.setVisibility(View.INVISIBLE);
			v_box_four.setVisibility(View.INVISIBLE);
			v_box_five.setVisibility(View.VISIBLE);

			tabHost.setCurrentTabByTag("His");

			mDrawerLayout.closeDrawers();
			
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);			
			break;
		case R.id.image_photo_left:
			Intent intent_photo = new Intent(MainActivity.this,
					UserInfoActivity.class);
			startActivity(intent_photo);
			mDrawerLayout.closeDrawers();
			break;
		case R.id.leftLayout:
			mDrawerLayout.closeDrawers();
			break;
		case R.id.rightLayout:
			mDrawerLayout.closeDrawers();
			break;
		case R.id.btn_logo:
			mDrawerLayout.openDrawer(leftLayout);
			break;
		default:
			break;
		}
	}

	private float progress;
	/**
	 * 箱包列表
	 */
	BaseAdapter rightAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			ViewHolder holder = null;

			if (view == null) {
				holder = new ViewHolder();
				view = LayoutInflater.from(MainActivity.this).inflate(
						R.layout.item_device_info, null);
				holder.relate_device = (RelativeLayout) view
						.findViewById(R.id.relate_device);
				holder.imageView = view.findViewById(R.id.v_show);
				holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
				holder.tv_address = (TextView) view
						.findViewById(R.id.tv_address);
				holder.btn_delete = (Button) view.findViewById(R.id.ib_delete);
				
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			int num = position + 1;
			holder.tv_name.setText(getText(R.string.box).toString() + num);
			holder.tv_address.setText(deviceInfos.get(position).getMac());

			if (mySharedPreferences.getBluAdress().equals(
					deviceInfos.get(position).getMac())) {
				holder.imageView.setVisibility(View.VISIBLE);
			} else {
				holder.imageView.setVisibility(View.INVISIBLE);
			}
			holder.btn_delete.setTag(position);
			holder.btn_delete.setOnClickListener(clickListener);

			return view;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void notifyDataSetChanged() {
			// TODO Auto-generated method stub
			super.notifyDataSetChanged();

//			float allleng = density * (getCount() + 1) * 60 + 1;
//
//			LayoutParams params = (LayoutParams) right_ListView
//					.getLayoutParams();
//			params.height = (int) allleng + 1;
//			right_ListView.setLayoutParams(params);
		}

		@Override
		public int getCount() {
			if (deviceInfos == null) {
				return 0;
			} else if (deviceInfos.size() > 3) {
				return 3;
			} else {
				return deviceInfos.size();
			}

		}

		OnClickListener clickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {

				switch (v.getId()) {
				case R.id.ib_delete:
					delete_position = (Integer) v.getTag();
					deleteDeviceInfoOnServer(deviceInfos.get(delete_position));
					showDeleteDialog(getText(R.string.delete_remind).toString());
					break;
				default:
					break;
				}
			}
		};
	};
	int delete_position = -1;

	private class ViewHolder {
		RelativeLayout relate_device;
		View imageView;
		View v_line;
		TextView tv_name;
		TextView tv_address;
		Button btn_delete;
	}

	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long arg3) {

			//点击设备列表 进行切换设备
			
			String  mac=deviceInfos.get(position)
					.getMac();
			
			if(mac.equals(mySharedPreferences.getBluAdress())){
				return;
			}
			
			application.swDevicesList.get(0).remove();
			mySharedPreferences.saveBluAdress(deviceInfos.get(position)
					.getMac());
			Intent intent = new Intent(MyService.ACTION_UPDATE_UI);
			intent.putExtra(Activity_0.Extra_RemoveScan, true); //2017-06-07 17:35:19 加的代码
			sendBroadcast(intent);
			intent = new Intent(MyService.ACTION_MYSERVICE);
			intent.putExtra(MyService.VALUE_TAG, 1);
			sendBroadcast(intent);
			deviceListChangeUI();
			
			 
		}
	};

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	// 确定删除
	void showDeleteDialog(String str) {
		final MyDialog myDialog = new MyDialog(MainActivity.this);
		myDialog.setContent(str);
		myDialog.getLeftButton().setText(getText(R.string.cancel));
		myDialog.getRighrButton().setText(getText(R.string.ok));
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();

			}
		});
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();
				// 删除解绑设备
				if (deviceInfos.get(delete_position).getMac()
						.equals(mySharedPreferences.getBluAdress())) {
					Log.e("tag", "delete mac*******************");
					dataBaseUtil.deleteDeviceInfo(
							mySharedPreferences.getPhoneNum(),
							deviceInfos.get(delete_position).getMac());
					application.swDevicesList.get(0).remove();
					
					mySharedPreferences.setNeedShowOADCaution(true);
					mySharedPreferences.saveBluAdress("");

					rightAdapter.notifyDataSetChanged();

					deviceInfos = dataBaseUtil
							.loadDeviceInfo(mySharedPreferences.getPhoneNum());
					if (deviceInfos != null && deviceInfos.size() > 0) {
						mySharedPreferences.saveBluAdress(deviceInfos.get(0)
								.getMac());

					}
					right_ListView.deleteItem();
					deviceListChangeUI();
					Intent intent = new Intent(MyService.ACTION_UPDATE_UI);
					sendBroadcast(intent);

					intent = new Intent(MyService.ACTION_MYSERVICE);
					intent.putExtra(MyService.VALUE_TAG, 1);
					sendBroadcast(intent);
				} else {
					Log.e("tag", "delete mac444444444444444444");
					dataBaseUtil.deleteDeviceInfo(
							mySharedPreferences.getPhoneNum(),
							deviceInfos.get(delete_position).getMac());
					deviceInfos.remove(delete_position);
					right_ListView.deleteItem();
					rightAdapter.notifyDataSetChanged();
					deviceListChangeUI();
				}

			}
		});

		myDialog.show();
	}

	 

	private void checkUpdate() {
		
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
		httpProgram.add("type",  "2"); //检测APP更新
		LogUtils.e("tag", " httpProgram:"+httpProgram.getPrograms().toString());
		
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.Check_Update_IP);
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(final String string) {
				LogUtils.e("tag", "Check_Update：" + string);
				try {
					JSONObject jsonObject = new JSONObject(string);
					int err = jsonObject.getInt("err");
					if (err == 0) {
						JSONArray jsonArray = jsonObject
								.getJSONArray("data");
						JSONObject object=jsonArray.getJSONObject(0);
						if(object.has("version")){
							int versionCode=object.getInt("version");
							int code = Util.getAppVersionCode(MainActivity.this);
							if (versionCode > code) {
								String apkURL=object.getString("file");
								if(!apkURL.startsWith("http://")){
									apkURL="http://"+apkURL;
								}
								MySharedPreferences.getInstance(MainActivity.this).saveAPKUrl(apkURL);
								showUpdateDialog();
							} 
						}
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				 
			}
		});
		 
	}

	public String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

	public void showUpdateDialog() {
		final MyDialog myDialog = new MyDialog(this);
		myDialog.setContent(R.string.soft_update_info);
		myDialog.setLeftButtonText(R.string.cancel);
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myDialog.dismiss();
			}
		});
		myDialog.setRightButtonText(R.string.ok);
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myDialog.dismiss();
				
				Intent downloadApk = new Intent(MainActivity.this,
						DownloadService.class);
				startService(downloadApk);
			}
		});

		myDialog.show();
	}

	@Override
	public void onDrawerClosed(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDrawerOpened(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDrawerSlide(View drawerView, float slideOffset) {
		View mContent = mDrawerLayout.getChildAt(0);
		View mMenu = drawerView;
		float scale = 1 - slideOffset;
		float rightScale = 0.8f + scale * 0.2f;

		if (drawerView.getTag().equals("LEFT")) {

			float leftScale = 1 - 0.3f * scale;

//			ViewHelper.setScaleX(mMenu, leftScale);
//			ViewHelper.setScaleY(mMenu, leftScale);
			ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
			ViewHelper.setTranslationX(mContent, mMenu.getMeasuredWidth()
					* (1 - scale));
			ViewHelper.setPivotX(mContent, 0);
//			ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
			mContent.invalidate();
//			ViewHelper.setScaleX(mContent, rightScale);
//			ViewHelper.setScaleY(mContent, rightScale);
		} else {
			ViewHelper.setTranslationX(mContent, -mMenu.getMeasuredWidth()
					* slideOffset);
			ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
//			ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
			mContent.invalidate();
//			ViewHelper.setScaleX(mContent, rightScale);
//			ViewHelper.setScaleY(mContent, rightScale);
		}

	}

	@Override
	public void onDrawerStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	protected void deleteDeviceInfoOnServer(DeviceInfo deviceInfo) {
		ComyouHttpProgram httpProgram = new ComyouHttpProgram();
	 
		String address=mySharedPreferences.getBluAdress();
		httpProgram.add("id", ""+deviceInfo.getServer_id());
		httpProgram.add("table", "device");
		
		ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
				+ "app/user/dele_excu");
		LogUtils.e("tag", " httpProgram:"+httpProgram.getPrograms().toString());
		
		httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

			@Override
			public void onResponse(final String string) {
				Log.e("tag", "删除设备信息：" + string);
  
			}

			@Override
			public void onFailure(String arg0, IOException arg1) {
				 
				 LogUtils.e("tag", "  删除设备信息："+arg1  );
			}
		});
		
	}
}
